package com.wulian.user.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aliyun.oss.common.utils.StringUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wulian.common.dto.UserInfo;
import com.wulian.common.entity.SysUser;
import com.wulian.common.exception.BusinessException;
import com.wulian.common.util.MD5;
import com.wulian.common.vo.ResultMoudel;
import com.wulian.user.dto.CompanyManagerResultDto;
import com.wulian.user.entity.CompanyManager;
import com.wulian.user.entity.SysDept;
import com.wulian.user.entity.SysDict;
import com.wulian.user.entity.SysUserRole;
import com.wulian.user.mapper.CompanyManagerMapper;
import com.wulian.user.mapper.SysDictMapper;
import com.wulian.user.mapper.SysRoleMapper;
import com.wulian.user.mapper.SysUserMapper;
import com.wulian.user.service.CompanyManagerService;
import com.wulian.user.service.SysDeptService;

import lombok.extern.slf4j.Slf4j;

/**
 *@Description:()
 * @author  caifulin
 * @date  2020/10/23 11:09
 * @version 1.0
 */
@Slf4j
@Service
@Transactional
public class CompanyManagerServiceImpl extends ServiceImpl<CompanyManagerMapper, CompanyManager> implements CompanyManagerService {

    @Autowired
    private CompanyManagerMapper companyManagerMapper;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysDictMapper sysDictMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public Integer save(CompanyManagerResultDto companyManagerDto) {
        CompanyManager companyManager = new CompanyManager();
        BeanUtils.copyProperties(companyManagerDto,companyManager);
        Integer flag = 0;
        if(null != companyManager.getCompanyId()){
            CompanyManager existParam = new CompanyManager();
            existParam.setDelFlag(null);
            existParam.setCompanyId(companyManager.getCompanyId());
            flag =  companyManagerMapper.updateById(companyManager);
        }else{
            String companyAdminName = companyManagerDto.getCompanyAdminName();
            Map<String,Object> checkUserMap = new HashMap<>();
            checkUserMap.put("username",companyAdminName);
            List<SysUser> sysUsers = sysUserMapper.selectByMap(checkUserMap);
            if(sysUsers != null && sysUsers.size() > 0){
                log.info("用户名已存在");
                throw new BusinessException(1,"用户名已存在");
            }

            String companyLogo = companyManager.getCompanyLogo();
            String companyName = companyManager.getCompanyName();
            if(StringUtils.isNullOrEmpty(companyLogo) || StringUtils.isNullOrEmpty(companyName)){
                return flag;
            }
            companyManager.setCreateTime(new Date());
            companyManager.setStatus(0);
            flag = companyManagerMapper.insert(companyManager);
            //当企业创建时，1、自动生成组织关系和对应的角色菜单权限
            SysDept sysDept = new SysDept();
            sysDept.setDelFlag("0");
            sysDept.setName(companyManager.getCompanyName());
            sysDept.setDeptCode(String.valueOf(new Date().getTime()));
            sysDept.setUpdateTime(new Date());
            sysDept.setCreateTime(new Date());
            sysDept.setParentId(1);
            sysDept.setCompanyId(companyManager.getCompanyId());
            Map<String,Integer> deptIdMap = sysDeptService.add(sysDept,companyManager.getCompanyId());
            //2、同时创建用户
            EntityWrapper<SysDict> sysDictEntityWrapper = new EntityWrapper<>();
            sysDictEntityWrapper.eq("del_flag","0");
            sysDictEntityWrapper.and().eq("type","initpassword");
            sysDictEntityWrapper.and().eq("value",2);
            List<SysDict> sysDicts = sysDictMapper.selectList(sysDictEntityWrapper);
            String initPassword = "123456";
            if(null != sysDicts && sysDicts.size() != 0 ){
                initPassword = sysDicts.get(0).getLabel();
            }
            Integer deptId = null;
            if(null != deptIdMap){
                deptId = deptIdMap.get("deptId");
            }else{
                log.info("机构信息错误");
                throw new BusinessException(2,"机构信息错误");
            }
            SysUser sysUser = new SysUser();
            sysUser.setPassword(MD5.sign(initPassword, null, "utf-8"));
            sysUser.setUsername(companyAdminName);
            sysUser.setName(companyAdminName);
            sysUser.setCreateTime(new Date());
            sysUser.setUpdateTime(new Date());
            sysUser.setDelFlag("0");
            sysUser.setDeptId(deptId);
            sysUser.setStatus(0);
            sysUser.setUserType("0");
            sysUser.setCompanyId(companyManager.getCompanyId());
            flag = sysUserMapper.insert(sysUser);
            //创建角色和用户之间的关系
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getUserId());
            sysUserRole.setRoleId(deptIdMap.get("roleId"));
            sysRoleMapper.createsysUserRole(sysUserRole);
        }
        return flag;
    }

    @Override
    public ResultMoudel fencun(CompanyManager companyManager, UserInfo currentUser) {
        ResultMoudel resultMoudel = new ResultMoudel();
        String[] roles = currentUser.getRoles();
        if(roles == null){
            return resultMoudel.error("用户信息异常");
        }
        boolean falsg = false;
        for(String role: roles){
            if(role.equals("admin")){
                falsg = true;
                break ;
            }
        }
        if(! falsg){
            return resultMoudel.error("用户信息异常");
        }

        if (null == companyManager || null == companyManager.getCompanyId()) {
            return resultMoudel.error("参数异常");
        }
        Date nowDate = new Date();
        Integer userId = currentUser.getSysUser().getUserId();


        companyManager.setUpdateTime(nowDate);
        companyManager.setManagerUserId(userId);

        Integer integer = companyManagerMapper.updateById(companyManager);
        if (integer == null) {
            return resultMoudel.error("操作失败");
        } else {
            return resultMoudel.success("操作成功");

        }
    }
}